package com.dongdongshop.fifter;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dongdongshop.common.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Autowired
    private JwtUtil jwtUtil;


    @Value("#{'${gateway.exclude.urls}'.empty ? null : '${gateway.exclude.urls}'.split(',') }")
    private Set<String> urls;


    private PathMatcher pathMatcher = new AntPathMatcher();

    //过滤器功能
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //通过请求,取出token,从请求头取出
        ServerHttpRequest request = exchange.getRequest();
        //获取当前请求路径
        String path = request.getURI().getPath();
        //先判断是否需要校验token
        for (String eurl: urls){
            if (pathMatcher.match(eurl,path)){
                return chain.filter(exchange);
            }
        }
        String token = request.getHeaders().getFirst("AutharizeToken");
        //如果token不存在就说明,没登录,无效的token
        if (token==null || "".equals(token)){
            response(exchange);
        }
        //如果token存在,就校验token是否合法
        //使用JwtUtil进行解析     如果解析失败就会抛异常
        try {
            jwtUtil.parseJwt(token);
        }catch (Exception e){
            return response(exchange);
        }
        return chain.filter(exchange);  //chain.filter(exchange)就是通过了
    }
    //如果网关有多个过滤器,此数字代表过滤器执行顺序,数字越小越先执行
    @Override
    public int getOrder() {
        return 0;
    }

    //封装token返回无效的方法
    private Mono<Void> response(ServerWebExchange exchange){
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        //这里在返回头添加编码，否则中文会乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        byte[] bytes = JSONObject.toJSONBytes(Result.Response(ResultEnum.TOKEN_IS_NULL_ERROR), SerializerFeature.WriteMapNullValue);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }

}
